<template>
    <div class="userinfo">
        <!-- <Header :isBack="isBack" v-bind:title="title"></Header> -->
        <div class="header padding-24 space-between bg-active" >
            <div class="h-back" @click="goBack"><img :src="back" alt=""></div>
            <div class="title fs-36 color-f">{{title}}</div>
            <!-- <div class="h-share"></div> -->
            <div class="h-right"></div>
        </div>
        <div class="img-list">
            <div class="list-item bg-f padding-24 space-between arrow-right">
                <p class="fs-32">头像</p>
                <div class="right bg-e yuan">
                    <img :src="userinfo.user_avator" alt="" class="yuan" v-if="userinfo.user_avator">
                    <input type="file"  ref="avatarInput" @change='updataimg($event,1)' accept="image/*" class="updata-input">
                </div>
            </div>
            <div class="list-item bg-f padding-24 space-between arrow-right">
                <p class="fs-32">个人主页背景</p>
                <div class="right bg-e">
                    <img :src="userinfo.background_photo" alt="" v-if="userinfo.background_photo">
                    <input type="file"  ref="avatarInput" @change='updataimg($event,2)' accept="image/*" class="updata-input">
                </div>
            </div>
            <div class="list-item bg-f padding-24 space-between arrow-right" v-if="userinfo.is_singer==1">
                <p class="fs-32">艺人主页背景</p>
                <div class="right bg-e">
                    <img :src="userinfo.singer_avator" alt="" v-if="userinfo.singer_avator">
                    <input type="file"  ref="avatarInput" @change='updataimg($event,3)' accept="image/*" class="updata-input">
                </div>
            </div>
        </div>
        <div class="info-list">
           <div class="list-item bg-f padding-24 space-between arrow-right">
               <p class="fs-32">昵称</p>
                <p class="right fs-32 color-9" @click="gotosetname">{{userinfo.nickname}}</p>
            </div>
            <div class="list-item bg-f padding-24 space-between arrow-right">
               <p class="fs-32">性别</p>
               <!-- <p class="right fs-32 color-9" v-if="sex==''" @click="tochoosesex">请选择</p> -->
               <select name="" id="" v-model="userinfo.sex" class="right fs-32 color-9" @change="setsex">
                   <option disabled value="">请选择</option>
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
               
            </div>
            <div class="list-item bg-f padding-24 space-between arrow-right">
               <p class="fs-32">生日</p>
               <p class="right fs-32 color-9" @click="openPicker">{{userinfo.birthday}}</p>
            </div>
            <div class="list-item bg-f padding-24 space-between arrow-right">
               <p class="fs-32">地区</p>
               <p class="right fs-32 color-9" @click="tochoosecity">{{userinfo.region||'请选择'}}</p>
            </div> 
        </div>
        <div class="individuality-signature bg-f padding-24 space-between arrow-right">
            <p class="fs-32">签名</p>
            <p class="color-9" @click="gotosetsignature">{{userinfo.write_name||'还没有签名'}}</p>
        </div>

        <div class="account bg-f padding-24 space-between arrow-right" @click="gotosetaccount">
            <p class="fs-32">账号和绑定设置</p>
        </div>

        <div class="citys" v-if="choosecity">
            <div class="space-between padding-24">
                <p @click="choosecity=false">取消</p>
                <p @click="surecity">确定</p>
            </div>
            <mt-picker :slots="myAddressSlots" @change="onMyAddressChange" class="city-picker"></mt-picker>
        </div>
        <mt-datetime-picker
            ref="picker"
            type="date"
            year-format="{value} 年"
            month-format="{value} 月"
            date-format="{value} 日"
            v-model="pickerValue"
            :startDate="startDate"
            :endDate="endDate"
            @confirm="handleConfirm"
            >
        </mt-datetime-picker>
    </div>
</template>
<script>
import myaddress from '../../../static/address.json'     //引入省市区数据
import { formatDate } from '../../../static/js/date';
export default {
    data(){
        return{
            back:require('../../assets/index/back.png'),
            choosecity:false,
            title:'我的资料',
            userinfo:'',
            startDate:new Date(),
            endDate:new Date(),
            myAddressSlots: [
                {
                    flex: 1,
                    defaultIndex: 1,    
                    values: Object.keys(myaddress),  //省份数组
                    className: 'slot1',
                    textAlign: 'center'
                }, {
                    divider: true,
                    content: '-',
                    className: 'slot2'
                }, {
                    flex: 1,
                    values: [],
                    className: 'slot3',
                    textAlign: 'center'
                },
                {
                    divider: true,
                    content: '-',
                    className: 'slot4'
                },
                {
                    flex: 1,
                    values: [],
                    className: 'slot5',
                    textAlign: 'center'
                }
            ],
            myaddress:'',
            pickerValue:null,
            signature:''
        }
    },
    created(){
        this.todata()
        this.getuserinfo();
    },
    mounted(){
        this.$nextTick(() => { //vue里面全部加载好了再执行的函数  （类似于setTimeout）
        this.myAddressSlots[0].defaultIndex = 0    
        // 这里的值需要和 data里面 defaultIndex 的值不一样才能够初始化
        //因为我没有看过源码（我猜测是因为数据没有改变，不会触发更新）
      });
    },
    methods:{
        getuserinfo() {
            var url = this.$host1 + `home/getPersonalMsg`;
            this.$axios.get(url).then(res => {
                //return
                if (res.status == 200) {
                    let resData = res.data;
                    if (resData.code == 200) {
                        this.userinfo=resData.data
                    } else if (resData.code == 0) {
                        // this.$router.push('/login');
                    } else {
                        this.AlertWin(resData.message);
                    }
                }
            })
            .catch(() => {
            this.AlertWin("网络错误！请稍后重试！");
            });
        },
        // 修改信息
        setuserinfo(){
            var data={
                user_avator:this.userinfo.user_avator,
                background_photo:this.userinfo.background_photo,
                // nickname:
                sex:this.userinfo.sex,
                birthday:this.userinfo.birthday,
                region:this.userinfo.region,
                // write_name
            }
            var url = this.$host1 + `home/editProfile`
            this.$axios.post(url,data).then(res => {
                console.log(res);
                //return
                if (res.status == 200) {
                    let resData = res.data;
                    if (resData.code == 200) {
                        this.AlertWin("修改成功");
                        //this.userinfo=resData.data
                    }else {
                        this.AlertWin(resData.message);
                    }
                }
            }).catch(() => {
                this.AlertWin("网络错误！请稍后重试！");
            });
        },
        // 歌手修改背景
        setsingeruserinfo(){
            var data={
                singer_avator:this.userinfo.singer_avator,
            }
            var url = this.$host1 + `home/editSingerBackground`
            this.$axios.post(url,data).then(res => {
                console.log(res);
                //return
                if (res.status == 200) {
                    let resData = res.data;
                    if (resData.code == 200) {
                        this.AlertWin("修改成功");
                        //this.userinfo=resData.data
                    }else {
                        this.AlertWin(resData.message);
                    }
                }
            }).catch(() => {
                this.AlertWin("网络错误！请稍后重试！");
            });
        },
        setsex(){
            //console.log(this.userinfo.sex)
            this.setuserinfo()
        },
        todata(){
            var str = '1950-01-01';
            // 转换日期格式
            str = str.replace(/-/g, '/'); // "2010/08/01";
            // 创建日期对象
            this.startDate = new Date(str);
            var str1 = '2020-12-31';
            // 转换日期格式
            str1 = str1.replace(/-/g, '/'); // "2010/08/01";
            // 创建日期对象
            this.endDate = new Date(str1);
        },
        updataimg(e,i) {
            var formdata1=new FormData();// 创建form对象
            var file = e.target.files[0];
            var reader = new FileReader();
            var that = this
            reader.readAsDataURL(file);
            reader.onload = function(e) {
                // if(i==1){
                //     that.userinfo.user_avator = this.result
                // }else if(i==2){
                //     that.userinfo.background_photo=this.result
                // }else if(i==3){
                //     that.userinfo.singer_avator=this.result
                // }
                
            }
            formdata1.append('file',file);
            let config = {
                headers:{'Content-Type':'multipart/form-data'}
            };
            var url =this.$host1 + `upload_file`
            this.$axios.post(url,formdata1,config).then((response) => {
                console.log(response)
                if(i==1){
                    that.userinfo.user_avator = response.data.dest
                    this.setuserinfo()
                }else if(i==2){
                    that.userinfo.background_photo=response.data.dest
                    this.setuserinfo()
                }else if(i==3){
                    that.userinfo.singer_avator=response.data.dest
                    this.setsingeruserinfo()
                }
                //this.AlertWin("上传成功！");
                //this.imgUrl1=response.data.dest
                //this.getuseridinfo(this.imgUrl1)
            })
        }, 
        tochoosecity(){
            this.choosecity=true
        },
        surecity(){
            this.choosecity=false
            if(this.myaddress[0]&&this.myaddress[1]&&this.myaddress[2]){
                this.userinfo.region= `${this.myaddress[0]}${this.myaddress[1]}${this.myaddress[2]}`
                this.setuserinfo()
            }else{
                this.AlertWin('请选择正确的区域！');
            }
            
            //this.area=this.myaddress
        },
        onMyAddressChange(picker, values) {
            if(myaddress[values[0]]){  //这个判断类似于v-if的效果（可以不加，但是vue会报错，很不爽）
                picker.setSlotValues(1,Object.keys(myaddress[values[0]])); // Object.keys()会返回一个数组，当前省的数组
                picker.setSlotValues(2,myaddress[values[0]][values[1]]); // 区/县数据就是一个数组
                this.myaddress= values
            }
        },
        openPicker(){
            this.$refs.picker.open();
        },
        handleConfirm(){
            var data=''
            data=formatDate(this.pickerValue,'yyyy-MM-dd')
            this.userinfo.birthday=data
            this.setuserinfo()
        },
        goBack(){
            this.$router.push('/account')
        },
        gotosetname(){
            this.$router.push('/setname')
        },
        gotosetsignature(){
            this.$router.push('/setsignature')
        },
        gotosetaccount(){
            this.$router.push('/setaccount')
        }
    }
}
</script>
<style lang="scss" scoped>
.userinfo{
    .header{
        width: 100%;
        height: 1rem;
        .h-back{
            width: 0.15rem;
            height: 0.26rem;
            img{
                //transform: rotate(180deg);
                width: 100%;
            }
        }
        .title{
            font-size: 0.36rem;
            font-weight: bold;
        }
        .h-right{
            width: 0.38rem;
            height: 0.5rem;
            img{
                display: inline-block;
                width: 100%;
            }
        }
        .h-share{
            position: absolute;
            right: 1rem;
            width: 0.45rem;
            height: 0.43rem;
            img{
                width: 100%;
                height: 100%;
            }
        }
    }
    .img-list{
        width: 100%;
        height: auto;
        margin-top: 1rem;
        //background-color: greenyellow;
        .list-item{
            height: 1.2rem;
            border-bottom: 0.01rem solid #e9e9e9;
            .right{
                width: 0.8rem;
                height: 0.8rem;
                position: absolute;
                right: 0.65rem;
                img{
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                    //border-radius: 50%;
                }
                .updata-input{
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    top: 0;
                    //background-color: greenyellow;
                    opacity:0;
                }
            }
        }
    }
    .info-list{
        margin-top: 0.2rem;
        .list-item{
            height: 1rem;
            position: relative;
            border-bottom: 0.01rem solid #e9e9e9;
            .right{
                width: auto;
                height: 0.8rem;
                position: absolute;
                right: 0.65rem; 
                line-height: 0.8rem;
                text-align: right;
            }
            select{
                direction: rtl; 
            }
        }
    }
    .citys{
        position: fixed;
        z-index: 999;
        background-color: #fff;
        bottom: 0;
        width: 100%;
        height: 5rem;
        overflow: hidden;
        box-shadow:0rem 0rem 0.1rem 0rem rgba(172,172,172,0.23);
        .space-between{
            height: 0.8rem;
            color: #3385ff;
            border-bottom: 0.01rem solid #e9e9e9;
        }
    }
    .individuality-signature{
        margin-top: 0.2rem;
        height: auto;
        min-height: 1rem;
        .fs-32{
            width: 1rem;
            //background-color: greenyellow;
        }
        .color-9{
            width: calc(100% - 1rem);
            //background-color: pink
        }
    }
    .account{
        height: 1rem;
        margin-top: 0.2rem;
        margin-bottom: 0.2rem;
    }
}
</style>
